<?php
/**
 * Created by PhpStorm.
 * User: meng
 * Date: 2021/7/6
 * Time: 11:07 下午
 */

namespace app\admin\model;


use app\lib\exception\BadRequestException;
use app\utils\TreeDataUtils;
use Carbon\Carbon;
use think\model\concern\SoftDelete;

class AdminMenuModel extends AdminBaseModel
{
    use SoftDelete;
    protected $table = 'admin_menu';

    protected $deleteTime = 'delete_time';
    protected $hidden = ['delete_time'];

    protected static $allowedFields = [
        'create' => ['title', 'parent_id', 'type', 'route_name', 'api_route_name', 'icon', 'cache', 'affix', 'breadcrumb', 'hidden', 'sort', 'remarks', 'create_time'],
        'update' => ['id', 'title', 'parent_id', 'type', 'route_name', 'api_route_name', 'icon', 'cache', 'affix', 'breadcrumb', 'hidden', 'sort', 'remarks', 'delete_time']
    ];

    const NOT_FOUND = 22000;
    const HAS_CHILDREN = 22004;

    public static function findMenu ($id) {
        $menu = self::find($id);
        if (empty($menu)) {
            throw new BadRequestException(self::NOT_FOUND);
        }
        return $menu;
    }

    public static function createMenu ($params) {
        $params['create_time'] = (string) Carbon::now();
        self::create($params, self::$allowedFields['create']);
    }

    public static function deleteMenu ($id) {
        $data = self::findMenu($id);
        $child = self::where('parent_id', $id)->find();
        if (!empty($child)) {
            throw new BadRequestException(self::HAS_CHILDREN);
        }
        $data->delete();
    }

    public static function updateMenu ($id, $params) {
        $menu = self::findMenu($id);
        $menu->allowField(self::$allowedFields['update'])->save($params);
    }

    public static function menuTree (): ?array {
        $list = self::select()->toArray();
        $tree = new TreeDataUtils($list, 'parent_id', 'id', 'children', null);
        return $tree->getTree();
    }
}
